package com.zw.cc.stock.service;

import com.zw.cc.stock.dao.QuotesPoMapper;
import com.zw.cc.stock.dao.StocksPoMapper;
import com.zw.cc.stock.model.QuotesPo;
import com.zw.cc.stock.model.StocksPo;
import com.zw.cc.stock.util.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhaowuz on 2018/1/9
 */
@Service
public class QuotesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(QuotesService.class);

    @Value("${quotes.url}")
    private String url;

    @Autowired
    private StocksPoMapper stocksMapper;

    @Autowired
    private QuotesPoMapper quotesPoMapper;

    /**
     * 定时每天更新 自选股行情
     */
    public void updateQuotes() {
        List<StocksPo> list  = stocksMapper.queryAll();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<QuotesPo> pos = new ArrayList<>();
        for (StocksPo stock : list) {
            QuotesPo quotesPo = getPriceNow(stock.getCode());
            if (null == quotesPo) {
                continue;
            }
            pos.add(quotesPo);
            if (pos.size()==100) {
                quotesPoMapper.insertOrUpdate(pos);
                LOGGER.info(">>>>>>>>更新行情数据 100 条");
                pos.clear();
            }
        }
        if (!CollectionUtils.isEmpty(pos)) {
            quotesPoMapper.insertOrUpdate(pos);
            LOGGER.info(">>>>>>>>更新行情数据 {} 条", pos.size());
        }
    }

    /**
     * 网络获取价格
     * @param code
     * @return
     */
    public QuotesPo getPriceNow(String code) {
        try {
            return HttpRequest.createBeans(url, code);
        } catch (Exception e) {
            LOGGER.error("###########网络查询  {} 行情失败",code);
        }
        return null;
    }

}
